package ru.amse.stroganova.ui.tool.state;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.event.MouseEvent;

import ru.amse.stroganova.ui.GraphComponent;
import ru.amse.stroganova.ui.tool.Tool;

class RectangleSelectionState extends ToolState {
	private final Tool tool;
	
	private final BasicStroke DASHED_STROKE = new BasicStroke(1.25f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10.0f, new float[]{2.5f}, 0.0f);
	
	private final GraphComponent component;
	
	private final ToolState selectionState;
	
	private final Point startPoint;

	private Point endPoint;
	
	/*package*/ RectangleSelectionState(GraphComponent component, Tool parentTool, Point startPoint, SelectionState selectionState) {
		this.component = component;
		this.selectionState = selectionState;
		tool = parentTool;
		this.startPoint = startPoint;
	}
	
	@Override
	public void mouseDragged(MouseEvent e) {
		endPoint = e.getPoint();
		component.getGraphElementSelection().unselect();
		component.getGraphElementSelection().selectInRect(startPoint.x,
				startPoint.y, endPoint.x, endPoint.y);
	}
	
	@Override
	public void mouseReleased(MouseEvent e) {
		endPoint = null;
		component.repaint();
		tool.setState(selectionState);
	}
	
	@Override
	public void paint(Graphics g, Color color) {
		if (endPoint != null) {
			//TODO Make constant
			Graphics2D gr2D = (Graphics2D) g;
			Stroke prevStroke = gr2D.getStroke();
			gr2D.setStroke(DASHED_STROKE);
			gr2D.setColor(new Color(10, 10, 205));
			int x = Math.min(startPoint.x, endPoint.x);
			int y = Math.min(startPoint.y, endPoint.y);
			int width = Math.abs(endPoint.x - startPoint.x);
			int height = Math.abs(endPoint.y - startPoint.y);
			gr2D.drawRect(x, y, width, height);
			gr2D.setStroke(prevStroke);
		}
	}
}
